<?php
/**
 * Classe Observer pour une commande de correction pour
 * - compter le nombre de mots
 * - changer la quantité
 * - recalculer le prix
 * @author NICPLE
 *
 */

ini_set('display_errors', 1);
error_reporting(E_ALL);
$_SERVER['MAGE_IS_DEVELOPER_MODE'] = "true";


define("DOC_AU_MOT_ATTRIBUTSET","Documents au mot");

define("CUSTOM_VAR_SENDER_EMAIL","correcteurs_mailing_list_email");
define("CUSTOM_VAR_SENDER_NAME","correcteurs_mailing_list_name");

// define("MAIL_GROUP_LANGUAGE_CODE","new_order_for_group_language");

define("LANGUE_DOC","Langue de votre document");
define("DELAY","Délais de traitement");

//Template EMAIL Base
define("CUSTOM_VAR_TEMPLATE_EMAIL_BASE","group_language_mail_template_");
define("CUSTOM_VAR_TEMPLATE_EMAIL_BASE_DEFAULT","group_language_mail_template_default");

// RECEIVER Base Name
define("CUSTOM_VAR_RECEIVER_GROUP_NAME","group_language_mailinglist_name_");
// RECEIVER Base Email
define("CUSTOM_VAR_RECEIVER_GROUP_EMAIL","group_language_mailinglist_email_");

//RECEIVER Default Name
define("CUSTOM_VAR_RECEIVER_GROUP_NAME_DEFAULT","group_language_mailinglist_name_default");
//RECEIVER Default Email
define("CUSTOM_VAR_RECEIVER_GROUP_EMAIL_DEFAULT","group_language_mailinglist_email_default");

//Delay to decrease on the customer delay option
define("CUSTOM_VAR_DELAI_DECREASE","group_language_delay_decrease_hour");

//Default AjusteQuoteItem Creation Historic
define("HIST_DEFAULT","Création d'une nouvelle commande au mot effective");

/**
 * Observer Front Class to intercept New validated Order
 * @author NICPLE
 *
*/
class Orthographe_WordCounter_Model_ObserverMailAfterSubmit extends Varien_Event_Observer
{
	public function __construct()
	{
	}


	/**
	 * Intercept Submit Validation to send extrat email to language Group of users
	 * @param Varien_Event_Observer $observer checkout_submit_all_after
	 */
	public function sendEmailToLanguageGroup(Varien_Event_Observer $observer) {

		Mage::log("NPL - ".get_class($this)." -BEGIN Send email to Group Language - observer : checkout_submit_all_after");

		$product = $observer->getEvent()->getProduct();
		// 		Mage::log($product->debug(),Zend_Log::DEBUG);






		// 			if(isset($observer['order'])){
		$session        = Mage::getSingleton('checkout/session');
		$quote_id       = $session->getQuoteId();
		$orderId		= $session->getOrderId();
		// 				$order     = Mage::getModel('sales/order')->loadByIncrementId($orderId);
		$order = $observer->getOrder();

		Mage::log("NPL - ".get_class($this)." -Order ID =  ".$order->getID()." / / / Quote ID = ".$order->getQuoteID(),Zend_Log::DEBUG);

		$quote = Mage::getSingleton('checkout/session')->getQuote();
		Mage::log("NPL - ".get_class($this)." -Quote =  ".isset($quote),Zend_Log::DEBUG);

		$sender = Array('name'  => Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_SENDER_NAME)->getValue('plain'),
				'email' => Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_SENDER_EMAIL)->getValue('plain'));

		Mage::log("NPL - ".get_class($this)." -Sender from CUSTOM_VAR_SENDER_EMAIL =  ".print_r($sender,true),Zend_Log::DEBUG);

		$storeID = Mage::app()->getStore()->getStoreId();
		Mage::log("NPL - ".get_class($this)." -Store ID= ".$storeID,Zend_Log::DEBUG);

		//Loop over quote Items
		$quoteItems = $quote->getItemsCollection();
		foreach ($quoteItems as $item){

			//Test si product au mot !
			//Check the new Product AttributeSet to test if it's a document au mot : DOC_AU_MOT_ATTRIBUTSET
			$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
			$attributeSetModel->load($item->getProduct()->getAttributeSetId());
			$attributeSetName  = $attributeSetModel->getAttributeSetName();

			Mage::log("NPL -  ".get_class($this)." - AttributeSetName = ".$attributeSetName,Zend_Log::DEBUG);

			if(0 == strcmp($attributeSetModel->getAttributeSetName(), DOC_AU_MOT_ATTRIBUTSET)){
				Mage::log("NPL -  ".get_class($this)." - Product is a ".DOC_AU_MOT_ATTRIBUTSET,Zend_Log::DEBUG);



				Mage::log("NPL - ".get_class($this)." -Getting Groups Language ",Zend_Log::DEBUG);
				$itemCustomOption = $this->identifyGroupLanguage($item);
				Mage::log("NPL - ".get_class($this)." -Groups Language =  ".print_r($itemCustomOption,true),Zend_Log::DEBUG);

				Mage::log("NPL - ".get_class($this)." -Preparing email to Groups Language {$itemCustomOption['language']}",Zend_Log::INFO);
				$arGroupEmailPrepared = $this->prepareGroupEmail($itemCustomOption, $order);
				Mage::log("NPL - ".get_class($this)." -Sending email to Groups Language {$itemCustomOption['language']}",Zend_Log::INFO);

				//Adding Order reference
				$arGroupEmailPrepared['order']=$order;

				$translate  = Mage::getSingleton('core/translate');

				Mage::getModel('core/email_template')->sendTransactional(
				$arGroupEmailPrepared['email_template_id'], //OK
				$sender, //OK
				$arGroupEmailPrepared['emails'],
				$arGroupEmailPrepared['receivers'],
				$arGroupEmailPrepared, //OK
				$storeID //OK
				);
				try {
					$translate->setTranslateInline(true);

					Mage::log("NPL - ".get_class($this)." -Group Language email SENT for order : # {$order->getID()}.",Zend_Log::INFO);

				}catch(Exception $e){
					Mage::log("NPL - ".get_class($this)." - Error in Group Email Message  !".$e->getMessage(),Zend_Log::DEBUG);
					Mage::log("NPL - ".get_class($this)." -Error Wile sending Group Language email for order #{$orderId} !",Zend_Log::ERR);
					Mage::getSingleton("core/session")->addWarning("Warning, sending email to group");
				}

				try{
					//Update AjusteOrder Quote Item
					$this->updateOrderIDForAjusteQuoteItem($order,$item,$quote,$arGroupEmailPrepared);
				}catch (Exception $e) {
					Mage::getSingleton("core/session")->addError("Error saving detail order");
				}


			} else {
				Mage::log("NPL -  ".get_class($this)." - Product is not a ".DOC_AU_MOT_ATTRIBUTSET." Normal Process apply",Zend_Log::INFO);
			}
		}
		Mage::log("NPL - ".get_class($this)." -END Send email to Group - observer : checkout_submit_all_after");
	}

	/**
	 * Send email to a Group regarding QuoteIte	m in the Cart
	 * @param array $arOptions
	 * @return $arOptions
	 */
	private function prepareGroupEmail(Array $arOptions, $order) {


		//Load Transactionnal email
		$emailTemplate  = Mage::getModel('core/email_template')->loadByCode(
				Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_TEMPLATE_EMAIL_BASE.$arOptions['language'])->getValue('plain')
		);
		//Test if the template is valid otherwise load the default one.
		if(!isset($emailTemplate) || !strlen($emailTemplate->getId()))
			$emailTemplate  = Mage::getModel('core/email_template')->loadByCode(
					Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_TEMPLATE_EMAIL_BASE_DEFAULT)->getValue('plain')
			);
		$arOptions['email_template_id'] = $emailTemplate->getId();
		Mage::log("NPL - ".get_class($this)." -Email Template new_order_for_group_language = ".$emailTemplate->getId()." - ".$emailTemplate['template_code'],Zend_Log::DEBUG);



		//Manager Receiver mail
		$recipients = Array();
		if(strlen($arOptions['language']) && strlen(Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_RECEIVER_GROUP_EMAIL.$arOptions['language'])->getValue('plain'))) {

			$email = CUSTOM_VAR_RECEIVER_GROUP_EMAIL.$arOptions['language'];
			// 			Mage::log("NPL - ".get_class($this)." -EMAIL  - ${arOptions['language']} ".strlen(Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_RECEIVER_GROUP_EMAIL.$arOptions['language'])->getValue('plain')));

			$recipients[Mage::getModel('core/variable')->loadByCode($email)->getValue('plain')] =
			Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_RECEIVER_GROUP_NAME.$arOptions['language'])->getValue('plain');

		}else{
			$recipients[Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_RECEIVER_GROUP_EMAIL_DEFAULT)->getValue('plain')] =
			Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_RECEIVER_GROUP_NAME_DEFAULT)->getValue('plain');

			// 			Mage::log("NPL - ".get_class($this)." -EMAIL DEFAULT - ".Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_RECEIVER_GROUP_EMAIL_DEFAULT)->getValue('plain'));

		}
		Mage::log("NPL - ".get_class($this)." -Email receiver = ".print_r($recipients,true),Zend_Log::DEBUG);

		$arOptions['emails'] =array_keys($recipients);
		$arOptions['receivers']=array_values($recipients);


		//Manage Delays = order Delay - CUSTOM_VAR_DELAI_DECREASE
		$arOptions['delay']=intval($arOptions['cmd_delay'])-intval(Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_DELAI_DECREASE)->getValue('plain'));
		Mage::log("NPL - ".get_class($this)." -Email Preparing with new delay = ".$arOptions['delay'],Zend_Log::DEBUG);

		//Manage Dead line regarding Order creation date and delay
		$dateTimestamp = Mage::getModel('core/date')->timestamp(
				Mage::helper('orthographewordcounter')->getDeadlineWorkingHour($order->getCreatedAt(),$arOptions['delay'])
		);
		$arOptions['dead_line']=date('d/m/Y H:i', $dateTimestamp);

		Mage::log("NPL - ".get_class($this)." -Email Preparing with deadline = ".$arOptions['dead_line'],Zend_Log::DEBUG);



		return $arOptions;

	}


	/**
	 * Identify Options and populate array to fill email data
	 * @param Mage_Sales_Model_Quote_Item $quoteItem
	 * @return array arOptions
	 */
	private function identifyGroupLanguage(Mage_Sales_Model_Quote_Item $quoteItem) {

		$arOptions = Array();

		//Getting the whole selected options
		$arOptions['label']=$quoteItem->getProduct()->getName();
		Mage::log("NPL - ".get_class($this)." -QuoteItem Product = ".$arOptions['label'],Zend_Log::DEBUG);

		$arOptions = $quoteItem->getProduct()->getTypeInstance(true)->getOrderOptions($quoteItem->getProduct());

		//Pass thrue the different custom options
		foreach($arOptions["options"] as $customOption) {

			Mage::log("NPL - ".get_class($this)." -Custom option activated ==> ".$customOption['label']." / value = ".print_r($customOption,true),Zend_Log::DEBUG);


			if($customOption['option_type']=='file')
				$arOptions['file']=$customOption['print_value'];
			$arOptions['Qty']=$quoteItem->getQty();

			//Getting the catalog production options bye ID
			if(intval($customOption['option_value'])){
				try {
					$value = Mage::getModel('catalog/product_option_value')->getCollection()
					->getValuesByOption($customOption['option_value'])
					->addTitleToResult(Mage::app()->getStore()->getId())
					->addPriceToResult(Mage::app()->getStore()->getId())
					->getFirstItem();



					// Populate Options
					switch($customOption['label']){
						case LANGUE_DOC :
							$arOptions['language']=$value->getSku();
							break;
						case DELAY :

							//Getting the Delay from the ajuste_quote_item in DB
							//Get the QuoteItem Object
							$ajusteQuoteItem = Mage::getModel('wordcounter/ajuste_quote_item')
							->load($quoteItem->getID(),'quote_item_id');

							$arOptions['cmd_delay']=$ajusteQuoteItem->getFinalDelay();



							break;
					}

					Mage::log("NPL - ".get_class($this)." - Valuable cust option retrieve ==> Title = ".$customOption["label"]."
							/ SKU = ".$value->getSku()." / Final Delay = ".$arOptions['cmd_delay'],Zend_Log::DEBUG);

				}catch(Exception $e) {
					Mage::log("NPL - ".get_class($this)." - Getting Custom Option details is not possible !".$e->getMessage(),Zend_Log::DEBUG);
				}
			}else{
				Mage::log("NPL - ".get_class($this)." -option_value is not Interger !".$customOption['option_value'],Zend_Log::DEBUG);
			}
		}
		return $arOptions;
	}

	/**
	 * Update AjusteQuote Item in Datase
	 * @param unknown $quoteItem
	 * @param unknown $quote
	 * @param unknown $arOptionsPrepared
	 */
	private function updateOrderIDForAjusteQuoteItem($order, $quoteItem,$quote,$arOptionsPrepared) {

		Mage::log("NPL - ".get_class($this)." - Quote ID to save = ".$order->getID(),Zend_Log::DEBUG);

		if($quote->getID()!=NULL){

			$ajusteQuoteItem = Mage::getModel('wordcounter/ajuste_quote_item')
			->load($quoteItem->getID(),'quote_item_id');


			Mage::log("NPL - ".get_class($this)." -Try to update AjustQuoteItem ID=".$ajusteQuoteItem->getId(),Zend_Log::INFO);
			$ajusteQuoteItem->setOrderItemID($order->getID());
			//Num de commande
			$ajusteQuoteItem->setOrderItemNum($order->getRealOrderId());
			// Date de commande
			$ajusteQuoteItem->setOrderItemDate($order->getCreatedAt());

			//Set Type of commande

			$productRef = Mage::getModel('catalog/product')
			->load($quoteItem->getName(),'name');

			$ajusteQuoteItem->setTypeCmd($productRef->getId());
			
			$ajusteQuoteItem->setTypeCmd($quoteItem->getProduct()->getId());
			
			//Set Language
			$ajusteQuoteItem->setLanguage($arOptionsPrepared['language']);
			//set Default Status
			$ajusteQuoteItem->setStatut(Mage::helper('orthographewordcounter')->getDefaultStatus());
			//Set Nbr Mot
			$ajusteQuoteItem->setNbrMots($quoteItem->getQty());
			//			$ajusteQuoteItem->setValideur();
			// 			$ajusteQuoteItem->setCorrecteur();
			//Set Correcteur Dead Line
			$ajusteQuoteItem->setCorrecteurDeadLine(
					Mage::getModel('core/date')->timestamp(
							Mage::helper('orthographewordcounter')->getDeadlineWorkingHour($order->getCreatedAt(),$arOptionsPrepared['delay'])
					));

			//Set Client Dead Line
			$ajusteQuoteItem->setClientDeadLine(
					Mage::getModel('core/date')->timestamp(
							Mage::helper('orthographewordcounter')->getDeadlineWorkingHour($order->getCreatedAt(),$arOptionsPrepared['cmd_delay'])
					));
			// 					Mage::app()->getLocale()->date(strtotime($quoteItem->getCreatedAt())+(intval($arOptionsPrepared['cmd_delay'])*60*60), null, null, false)->toString('Y-m-d H:i:s'));
			//Set Last update timestamp
			$ajusteQuoteItem->setLastUpdate(time());
			//Set Historic
			$ajusteQuoteItem->setHistoric(Mage::helper('orthographewordcounter')->formatHistoricDBHistoric($ajusteQuoteItem,HIST_DEFAULT));

			try{
				Mage::log("NPL - ".get_class($this)." - ***************************************************************************",Zend_Log::INFO);
				Mage::log("NPL - ".get_class($this)." - AjusteQuoteItem to update ".print_r($ajusteQuoteItem,true),Zend_Log::DEBUG);
				$ajusteQuoteItem->save();
				Mage::log("NPL - ".get_class($this)." -AjusteQuoteItem updated with success ID=".$ajusteQuoteItem->getId(),Zend_Log::INFO);
				Mage::log("NPL - ".get_class($this)." - ***************************************************************************",Zend_Log::INFO);
			}catch(Exception $e){
				Mage::log("NPL -  ".get_class($this)." - ERROR while saving the Ajuste QuoteItem in Database ".print_r($ajusteQuoteItem,true),Zend_Log::ERROR);
				Mage::getSingleton("core/session")->addError("Error saving detail order");
			}
		}else{
			Mage::log("NPL - ".get_class($this)." -Error Quote ID is NULL ",Zend_Log::DEBUG);
		}
	}

}
